package com.zxy.service;


import cn.echo.exception.BizException;
import cn.hutool.core.util.ObjectUtil;
import com.zxy.dao.InventoryDao;
import com.zxy.dao.InventoryLogDao;
import com.zxy.dao.OoItemDao;
import com.zxy.model.Inventory;
import com.zxy.model.InventoryLog;
import com.zxy.model.OoItem;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class OoItemService {

    @Resource
    private OoItemDao ooItemDao;
    @Resource
    private InventoryDao inventoryDao;
    @Resource
    private InventoryLogDao inventoryLogDao;

    public int insert(OoItem model) {
        Inventory inventory = inventoryDao.selectById(model.getProductId());
        if (ObjectUtil.isEmpty(inventory)) throw new BizException(707, "库存中无此商品");
        int beforeQty = inventory.getQty();
        int afterQty = beforeQty - model.getQty();
        if (afterQty < 0) {
            throw new BizException(707, "数量异常");
        }
        inventory.setQty(afterQty);
        inventory.setSaleCount(inventory.getSaleCount() + model.getQty());
        inventoryDao.update(inventory);
        insertLog(model, beforeQty, afterQty);
        model.setProductName(inventory.getProductName());
        model.setShelfId(inventory.getShelfId());
        return ooItemDao.insert(model);
    }

    private void insertLog(OoItem ooItem, int beforeQty, int afterQty) {
        InventoryLog inventoryLog = new InventoryLog();
        inventoryLog.setProductId(ooItem.getProductId());
        inventoryLog.setBeforeQty(beforeQty);
        inventoryLog.setOptionQty(ooItem.getQty());
        inventoryLog.setAfterQty(afterQty);
        inventoryLog.setOptionType(-1);
        inventoryLog.setRefId(ooItem.getOoId());
        inventoryLogDao.insert(inventoryLog);
    }
}
